import React, { Fragment, useState, useEffect, useReducer } from 'react';
import { Button, Card } from 'antd';
import MyForm from './components/MyForm';
import MyModal from './components/MyModal';
import TableList from './components/TableList';
import { SIZE, PAGE, ALL } from '@/utils/constant';
import { msgList, messageType } from '@/services/api';

interface initial {
  loading: boolean;
  data: [];
  pagination: object;
  searchValue: object;
}

const initialState: initial = {
  loading: false,
  data: [],
  pagination: {
    showSizeChanger: true,
  },
  searchValue: {},
};

const reducer = (state: any, { type, payload }: any) => {
  switch (type) {
    case 'OPEN_LOADING':
      return {
        ...state,
        loading: true,
      };
    case 'CLOSED_LOADING':
      return {
        ...state,
        loading: false,
      };
    case 'GET_DATA':
      return {
        ...state,
        data: payload,
      };
    case 'CHANGE_PAGINATION':
      return {
        ...state,
        pagination: payload,
      };
    case 'SEARCH_VALUE':
      return {
        ...state,
        searchValue: payload,
      };
    default:
      return state;
  }
};

const columns = [
  {
    title: '标题',
    key: 'title',
    dataIndex: 'title',
  },
  {
    title: '消息类型',
    key: 'receive_type',
    dataIndex: 'receive_type',
    render: (text: any) => (text === 1 ? <span>个人消息</span> : <span>系统消息</span>),
  },
  {
    title: '创建者',
    key: 'sender',
    dataIndex: 'sender',
    render: (text: any) => <span>{text && text.name}</span>,
  },
  {
    title: '接收家长',
    key: 'receiver',
    dataIndex: 'receiver',
    render: (text: any) => <span>{text && text.name}</span>,
  },
  {
    title: '创建时间',
    key: 'created_at',
    dataIndex: 'created_at',
  },
  {
    title: '内容',
    key: 'content',
    width: '60%',
    dataIndex: 'content',
  },
];

const Message = () => {
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [msgType, setMsgType] = useState([]);
  const [{ loading, data, pagination, searchValue }, dispatch]: any = useReducer(
    reducer,
    initialState,
  );
  const pager = JSON.parse(JSON.stringify(pagination));
  useEffect(() => {
    dispatch({
      type: 'OPEN_LOADING',
    });
    msgList({ page: PAGE, size: SIZE })
      .then((res: any) => {
        if (res.status === 'success') {
          dispatch({
            type: 'GET_DATA',
            payload: res.data.data,
          });
          dispatch({
            type: 'CHANGE_PAGINATION',
            payload: {
              ...pager,
              total: res.data.meta.total,
            },
          });
        }
        dispatch({
          type: 'CLOSED_LOADING',
        });
      })
      .catch(() => {
        dispatch({
          type: 'CLOSED_LOADING',
        });
      });
    messageType({ page: PAGE, size: ALL }).then((resp: any) => {
      if (resp.status === 'success') {
        setMsgType(resp.data.data);
      }
    });
  }, []);

  const onChange = (changePagination: any) => {
    pager.current = changePagination.current;
    pager.pageSize = changePagination.pageSize;
    dispatch({
      type: 'CHANGE_PAGINATION',
      payload: pager,
    });
    dispatch({
      type: 'OPEN_LOADING',
    });
    msgList({ ...searchValue, page: changePagination.current, size: changePagination.pageSize })
      .then((res: any) => {
        if (res.status === 'success') {
          dispatch({
            type: 'GET_DATA',
            payload: res.data.data,
          });
          dispatch({
            type: 'CHANGE_PAGINATION',
            payload: {
              ...pager,
              total: res.data.meta.total,
            },
          });
        }
        dispatch({
          type: 'CLOSED_LOADING',
        });
      })
      .catch(() => {
        dispatch({
          type: 'CLOSED_LOADING',
        });
      });
  };

  return (
    <Fragment>
      <Card
        title="消息列表"
        extra={
          <Button
            onClick={() => {
              setIsModalVisible(true);
            }}
            type="primary"
            icon="plus"
          >
            新增消息
          </Button>
        }
      >
        <MyForm dispatch={dispatch} msgList={msgList} />
      </Card>
      <Card className="pageCard">
        <TableList
          rowKey="id"
          dataSource={data}
          columns={columns}
          loading={loading}
          pagination={pagination}
          onChange={onChange}
        />
      </Card>
      {isModalVisible && (
        <MyModal
          onClosed={() => {
            setIsModalVisible(false);
          }}
          msgType={msgType}
          dispatch={dispatch}
        />
      )}
    </Fragment>
  );
};

export default Message;
